/**
 * @author re0hg
 * @version 1.0
 * @date 2025/3/28
 */
package networkListener;

import org.pcap4j.core.*;
import org.pcap4j.packet.*;
import org.pcap4j.packet.namednumber.TcpPort;

import java.util.Date;

public class NetworkListener {

    private PcapHandle handle;
    private CsvLogger csvLogger = new CsvLogger();

    public NetworkListener(PcapNetworkInterface device) throws PcapNativeException {
        this.handle = device.openLive(65536, PcapNetworkInterface.PromiscuousMode.PROMISCUOUS, 1000);
    }

    public void startListening() {
        PacketListener listener = packet -> {
            //System.out.println("Captured packet: " + packet);  // 打印捕获的包
            PacketProcessor processor = new PacketProcessor(packet);
            String[] packetData = processor.processPacket();
            if (packetData != null) {
                String timestamp = new Date().toString();
                csvLogger.logToCsv(timestamp, packetData);
                System.out.println("Processed packet: " + packetData[0] + " -> " + packetData[2] +
                        ", User: " + packetData[4] + ", Password: " + packetData[5] +
                        ", Status: " + packetData[6]);
            }
        };

        try {
            handle.loop(-1, listener);
        } catch (PcapNativeException | NotOpenException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void stopListening() {
        if (handle != null && handle.isOpen()) {
            handle.close();
        }
    }
}
